package cc.wanforme.st.server.config;

import java.util.Arrays;
import java.util.List;

import cc.wanforme.fsync.client.ClientProperty;
import cc.wanforme.fsync.config.ClientInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import cc.wanforme.st.server.interceptor.RefererInterceptor;
import cc.wanforme.st.server.properties.CsrfCorsProperty;

/** 配置请求头 Origin 和 referer 限制。
 * @author wanne
 * @date 2022-10-24
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	
	@Autowired
	private CsrfCorsProperty csrfCorsProperty;
	@Autowired
	private ClientProperty clientProperty;
	
	/** referer 防 盗链
	 * @return
	 */
	public RefererInterceptor refererInterceptor() {
		String[] refers = csrfCorsProperty.getRefers();
		if(csrfCorsProperty.isEnableRefers() && refers!= null) {
			List<String> list = Arrays.asList(refers);
			return new RefererInterceptor(list, csrfCorsProperty.isAllowEmptyReferer());
		}
		return null;
	}
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		RefererInterceptor interceptor = this.refererInterceptor();
		if(interceptor != null) {
			registry.addInterceptor(interceptor).addPathPatterns("/**");
		}

		// 拦截 /client/** 下的所有 url，对请求头进行验证
		registry.addInterceptor(new ClientInterceptor(clientProperty.getHttpHeader(),
						clientProperty.getHttpValue()))
				.addPathPatterns("/client/**");
	}
	
	
	/**
	 * 配置 Origins 域名
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		CorsRegistration corsReg = registry.addMapping("/**");
		// 允许跨域的域名
		if(csrfCorsProperty.isEnableOrigins() && csrfCorsProperty.getOrigins() != null) {
			corsReg.allowedOriginPatterns(csrfCorsProperty.getOrigins());
		} else {
			corsReg.allowedOriginPatterns("*");
		}
		
		// 是否允许证书
		//corsReg.allowCredentials(true)
		// 允许的方法
		corsReg.allowedMethods("*")
		// 允许跨域的时间
		.maxAge(3600);
	}
	
}
